<?php
/**
 * @author guoxiaoyong
 */
namespace api\controllers;

use bc\controller\ApiController;
use bc\util\Util;
use bc\model\api\AppTokenModel;

class SpokesmanbaseController extends ApiController
{

	public function init()
	{
		$token = $this->post('token','');
		if(empty($token))
		{
			if($_SERVER['REDIRECT_URL']==='/spokesman/login' || $_SERVER['REDIRECT_URL']==='/spokesman/getcode' || $_SERVER['REDIRECT_URL']==='/spokesman/register')
			{

			}else{
				$this->echoJosnpData(1,array(),'请重新登录');
			}
		}else{
			//验证token
			$this->loginByToken($token);
		}
	}

	//返回josnp数据
    public function echoJosnpData($error=0,$data=array(),$msg='请求成功')
	{
		Util::echoJosnpData($error,$data,$msg);
	}

    /**
     * 登录
     */
	public function login($moblie,$code,$code_id)
	{
		$appTokenM = new AppTokenModel();
		$token = $appTokenM->checklogin($moblie,$code,$code_id);
		if(!$token){
			$this->echoJosnpData(1,array(),'失败');
		}
		$this->echoJosnpData(0,['token'=>$token],'成功');
	}

    /**
     * 登录from token
     */
	public function loginByToken($token)
	{
		$appTokenM = new AppTokenModel();
		$status = $appTokenM->checkToken($token);
		if(!$status){
			$this->echoJosnpData(1,array(),'失败');
		}
	}

    /**
     * 注册
     */
	public function register($moblie,$code,$code_id)
	{
		$appTokenM = new AppTokenModel();
		$token = $appTokenM->checklogin($moblie,$code,$code_id);
        if(!$token){
            $this->echoJosnpData(1,array(),'失败');
        }
        $this->echoJosnpData(0,['token'=>$token],'成功');
	}

    /**
     * 退出登录
     */
    public function logout($token)
    {
        $appTokenM = new AppTokenModel();
        $appTokenM->updateAll(['expiration_time'=>time(),'update_time'=>time()],['token_id'=>$token]);
        $this->echoJosnpData(0,[],'退出成功');
    }

	/**
	 * Description:根据token 返回对应用户指定的信息
	 */
	protected function getUserInfoByToken($token)
	{
        $appTokenM = new AppTokenModel();
        $appTokenD = $appTokenM->getRow(['token_id'=>$token]);
        return $appTokenD['user_id'];
	}

}

